package net.dgg.zz.api.production.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.commons.qds.model.LoginUser;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.api.credential.entity.CertificateProductConfiguration;
import net.dgg.zz.api.credential.service.CertificateProductConfigurationService;
import net.dgg.zz.api.production.dto.BottomDataSyncVo;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.utils.*;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.UnderOder;
import net.dgg.zz.production.entity.UnderOderProduct;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.UnderOrderDao;
import net.dgg.zz.production.inProcess.dao.UnderOrderProductDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>@Title 生产部分对外接口service</p>
 * <p>@Description 办理中Service</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author sdx</p>
 * <p>@date 2021年2月19日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ApiUnderOrderService extends BaseService {

    @Autowired
    private ProductOrderDao productOrderDao;

    @Autowired
    private UnderOrderDao underOrderDao;

    @Autowired
    private UnderOrderProductDao underOrderProductDao;

    @Autowired
    private CertificateProductConfigurationService certificateProductConfigurationService;

    @Autowired
    private InitComponent initComponent;

    /**
     * 返回跳转底单页面
     */
    public Object returnUrl(String busOrder, String busChildOrder, String returnUrl,
                            String notifyUrl, final boolean isOrderCenter){
        //转换销售主订单
        JSONObject order = JSONObject.parseObject(busOrder);
        Long orderId = order.getLong("orderId");
        JSONArray busOrders = JSONArray.parseArray(busChildOrder);
        boolean flag = true;
        for(int i=0;i<busOrders.size();i++) {
            JSONObject jsonObject = busOrders.getJSONObject(i);
            //筛选出需要填写底单的产品。。配置
            Map params = new HashMap();
            params.put("orderId",jsonObject.getLong("orderId"));
            params.put("orderBusId",jsonObject.getLong("orderBusId"));
            Long productId = jsonObject.getLong("productId");
            CertificateProductConfiguration certificateProductConfiguration = certificateProductConfigurationService.selectQyByProductId(productId);
            //将需要填写底单的产品插入资质生产数据库
            if(null != certificateProductConfiguration){
                int count = underOrderProductDao.selectCount(params);
                if(count < 1){
                    UnderOderProduct underOderProduct = new UnderOderProduct();
                    underOderProduct.setId(DggKeyWorker.nextId());
                    underOderProduct.setOrderId(orderId);
                    underOderProduct.setOrderNo(order.getString("orderNo"));
                    underOderProduct.setOrderBusId(jsonObject.getLong("orderBusId"));
                    underOderProduct.setOrderBusNo(jsonObject.getString("orderBusNo"));
                    underOderProduct.setProductId(productId);
                    underOderProduct.setProductName(jsonObject.getString("productName"));
                    underOderProduct.setStatus(0);
                    underOrderProductDao.insert(underOderProduct);
                }
            }else{
                //无需填写底单通知订单中心调整底单状态
                JSONObject json = new JSONObject();
                json.put("orderId", orderId);
                json.put("orderBusinessIds", jsonObject.getLong("orderBusId"));
                json.put("loginUser",null);
                MQMessageSendUtil.underOrderStatus(json);
                flag = false;
            }
        }
        //返回底单编辑页面
        String returnUnderOrderUrl = initComponent.getZzscUrl()+"/api/zzsc/under_order/edit.html?orderId=" + orderId;
        JSONObject jsonObject = JSONUtils.fastBuild("redirect", returnUnderOrderUrl + "&isOrderCenter=" + isOrderCenter);
        jsonObject.put("isUnderOrder", flag);
        return jsonObject;
    }

    /**
     * 跳转编辑业务底单公共资源统一处理
     *
     * @param isEdit          : 是否是修改
     * @param businessMark    : 业务标识    现在这个值，应该修改为，当前求这个借口 tab页的名称和url地址 用于回调关闭
     * @param model           : 返回对象
     * @param orderId      : orderId 销售订单ID
     * @return
     */
    public String underOrderIndex( boolean isEdit, Long orderId, String businessMark, Model model){
        ExceptionUtils.debug("业务底单公共资源统一处理 :{}",  isEdit, orderId, businessMark);
        Map map = new HashMap();
        model.addAttribute("orderId",orderId);
        //查询出资质需要填写底单的产品
        map.put("orderId",orderId);
        List<UnderOderProduct> products = underOrderProductDao.selectByOrderId(orderId);
        model.addAttribute("products",products);
        if(!CollectionUtils.isEmpty(products)){
            //资质底单已填写，返回已填写的底单数据
            if(products.get(0).getStatus() == 1){
                isEdit = false;
                List<UnderOder> underOders = underOrderDao.selectByOrderId(orderId);
                model.addAttribute("underOders",underOders);
            }
        }
        //证书类型
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        model.addAttribute("isEdit",isEdit);
        return "zzsc/underOrder/under_order";
    }

    /**
     * 保存底单
     * @param orderId
     * @param params
     */
    public void saveUnderOrder(Long orderId, String params){
        if(StringUtils.isEmpty(params)){
            throw new ProductOrderExcption("提交失败，请联系管理员！");
        }
        List<ProductOrder> list = productOrderDao.queryAllScorder(orderId);
        if(list.size() > 0){
            throw new ProductOrderExcption("该订单已分配，无法再次修改");
        }
        //根据销售底单查询底单数据
        List<UnderOder> underOders = underOrderDao.selectByOrderId(orderId);
        //查询到数据优先删除数据
        if(underOders.size() > 0){
            underOrderDao.deleteByOrderId(orderId);
        }
        //底单数据格式化
        JSONArray jsonArray = JSONArray.parseArray(params);
        //保存底单信息
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            UnderOder underOder = new UnderOder();
            Long id = DggKeyWorker.nextId();
            underOder.setId(id);
            underOder.setOrderId(jsonObject.getLong("orderId"));
            underOder.setOrderBusId(jsonObject.getLong("orderBusId"));
            underOder.setProductId(jsonObject.getLong("productId"));
            underOder.setCertificateTypeId(jsonObject.getLong("certificateType"));
            underOder.setCertificateType(jsonObject.getString("certificateTypeName"));
            underOder.setCertificateSpecialtyId(jsonObject.getString("certificateSpecialtys"));
            underOder.setCertificateSpecialty(jsonObject.getString("certificateSpecialtysName"));
            underOder.setCertificateLevel(jsonObject.getString("certificateLevel"));
            underOder.setCertificateLevelName(jsonObject.getString("certificateLevelName"));
            underOder.setIsSocialSecurity(jsonObject.getInteger("isSocialSecurity"));
            underOder.setSocialSecurityAreaId(jsonObject.getString("socialSecurityAreaId"));
            underOder.setSocialSecurityArea(jsonObject.getString("socialSecurityAreaChange"));
            underOder.setIsNeedOriginal(jsonObject.getInteger("isNeedOriginal"));
            underOder.setIsNeedAppearance(jsonObject.getInteger("isNeedAppearance"));
            underOder.setCount(jsonObject.getInteger("count"));
            underOrderDao.insert(underOder);
            //完善底单，通知订单中心
            JSONObject json = new JSONObject();
            json.put("orderId", jsonObject.getString("orderId"));
            json.put("orderBusinessIds", jsonObject.getLong("orderBusId"));
            json.put("loginUser",null);
            MQMessageSendUtil.underOrderStatus(json);
            //完善底单，通知生产中心
            BottomDataSyncVo bottomDataSyncVo = new BottomDataSyncVo();
            bottomDataSyncVo.setOrderId(jsonObject.getString("orderId"));
            bottomDataSyncVo.setOrderBusinessIds(jsonObject.getString("orderBusId"));
            bottomDataSyncVo.setUnderOrderId(id.toString());
            bottomDataSyncVo.setLoginUser(null);
            MQMessageSendUtil.notifyProduction(bottomDataSyncVo);
        }
        //修改产品底单状态
        underOrderProductDao.updateStatus(orderId);
    }
}
